#pragma once

#include "StorageManager.h"
#include <unordered_map>
#include <string>
#include <vector>
#include "common_types.h" // 包含统一的类型定义
namespace MiniDB
{

   
    struct CatalogEntry
    {
        std::string table_name;
        std::vector<ColumnInfo> columns;
        int root_page_id;
        size_t record_count;
        size_t total_size;

        CatalogEntry() : root_page_id(-1), record_count(0), total_size(0) {}
        CatalogEntry(const std::string &name) : table_name(name), root_page_id(-1), record_count(0), total_size(0) {}
    };

    // 系统目录 - 管理数据库元数据
    class SystemCatalog
    {
    public:
        SystemCatalog(std::shared_ptr<StorageManager> storage_manager);
        ~SystemCatalog();

        // 表管理
        bool createTable(const std::string &table_name, const std::vector<ColumnInfo> &columns);
        bool dropTable(const std::string &table_name);
        bool tableExists(const std::string &table_name) const;
        std::vector<std::string> getTableNames() const;

        // 表信息查询
        const CatalogEntry *getTableEntry(const std::string &table_name) const;
        bool updateTableStats(const std::string &table_name, size_t record_count, size_t total_size);

        // 持久化
        bool saveCatalog();
        bool loadCatalog();

        // 调试
        void printCatalog() const;

        // 恢复StorageManager中的表信息
        void restoreTablesInStorageManager();

    private:
        std::shared_ptr<StorageManager> storage_manager_;
        std::unordered_map<std::string, CatalogEntry> catalog_entries_;
        int catalog_page_id_;
        bool is_dirty_;

        // 序列化/反序列化
        bool serializeCatalog(std::vector<char> &buffer) const;
        bool deserializeCatalog(const std::vector<char> &buffer);
        bool serializeEntry(const CatalogEntry &entry, std::vector<char> &buffer) const;
        bool deserializeEntry(const std::vector<char> &buffer, CatalogEntry &entry, size_t &offset) const;

        // 页面管理
        bool allocateCatalogPage();
    };

} // namespace MiniDB
